﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Taobao.WangWang.Common;
using System.Threading;
using System.Configuration;

namespace Taobao.WangWang.ConsoleApp
{
    class Program
    {
        private DateTime minDatetime = DateTime.Today.AddDays(-1);
        private DateTime maxDatetime = DateTime.Today.AddDays(-1);
        private int fixDis = 7;

        static void Main(string[] args)
        {
            DateTime startDate = DateTime.Today.AddDays(-7);
            DateTime endDate = DateTime.Today.AddDays(-1);
            if (args.Length >= 1)
            {
                DateTime.TryParse(args[0], out startDate);
                if (args.Length >= 2)
                {
                    DateTime.TryParse(args[1], out endDate);
                }
                endDate = startDate.AddDays(6).CompareTo(endDate) > 0 ? endDate : startDate.AddDays(6);
            }
            else
            {
                string startDateInConfig = ConfigurationManager.AppSettings["StartDate"];
                if(!string.IsNullOrEmpty(startDateInConfig))
                {
                    DateTime.TryParse(startDateInConfig, out startDate); 
                    endDate = startDate.AddDays(6).CompareTo(endDate) > 0 ? endDate : startDate.AddDays(6);
                }
            }

            if (endDate.Subtract(startDate).Days >= 6)
            {
                startDate = endDate.AddDays(-6);
            }

            Console.WriteLine("程序开始");
            using (var entities = Model.Util.LoadEntities())
            {
                var allShops = entities.Shops.Include("ShopManagers").ToList();
                foreach (var shop in allShops)
                {
                    try
                    {
                        Console.WriteLine(string.Format("开始下载店铺:{0}的聊天记录", shop.Name));
                        WangWangProcessor processor = new WangWangProcessor(shop);
                        processor.StartDate = startDate;
                        processor.EndDate = endDate;
                        processor.Process();
                        Console.WriteLine(string.Format("下载店铺:{0}的聊天记录结束", shop.Name));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("下载店铺:{0}的聊天记录异常", shop.Name));
                    }
                }
            }
            Thread.Sleep(3000);
            Console.WriteLine("程序完成");
            //Console.ReadKey();
        }
    }
}
